// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const { phoneNumber, code } = event
  const db = cloud.database()
  const _ = db.command
  
  try {
    // 查询验证码记录
    const result = await db.collection('sms_codes')
      .where({
        phoneNumber,
        code,
        expireTime: _.gt(db.serverDate()) // 验证码未过期
      })
      .orderBy('createTime', 'desc')
      .limit(1)
      .get()

    if (result.data.length > 0) {
      // 验证成功后删除验证码记录
      await db.collection('sms_codes').doc(result.data[0]._id).remove()
      
      return {
        success: true
      }
    } else {
      return {
        success: false,
        message: '验证码无效或已过期'
      }
    }
  } catch (err) {
    console.error('验证失败：', err)
    return {
      success: false,
      error: err
    }
  }
} 